package com.jgdt.tools.decrypt.rest;

import com.jgdt.tools.decrypt.annotation.Decrypt;
import com.jgdt.tools.decrypt.config.EncryptProperties;
import com.jgdt.tools.decrypt.utils.AESUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;

/**
 * <p>
 *
 * </p>
 *
 * @author chang.zhou
 * @version 1$
 * @date Created in 2021/6/3 14:22
 */
@ControllerAdvice
@EnableConfigurationProperties(EncryptProperties.class)
public class DecryptRequest extends RequestBodyAdviceAdapter {
    Logger logger = LoggerFactory.getLogger(DecryptRequest.class);

    private EncryptProperties encryptProperties;

    public DecryptRequest(EncryptProperties encryptProperties) {
        this.encryptProperties = encryptProperties;
    }

    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return methodParameter.hasMethodAnnotation(Decrypt.class)
                || methodParameter.hasParameterAnnotation(Decrypt.class);
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        byte[] body = new byte[inputMessage.getBody().available()];
        inputMessage.getBody().read(body);
        try {
            byte[] decrypt = AESUtil.decrypt(body, this.encryptProperties.getKey().getBytes());
            final ByteArrayInputStream inputStream = new ByteArrayInputStream(decrypt);
            return new HttpInputMessage() {
                @Override
                public InputStream getBody() throws IOException {
                    return inputStream;
                }

                @Override
                public HttpHeaders getHeaders() {
                    return inputMessage.getHeaders();
                }
            };
        } catch (Exception e) {
            logger.error("DecryptRequest/Exception", e);
        }
        return super.beforeBodyRead(inputMessage, parameter, targetType, converterType);
    }
}
